<template>
  <div class="order-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :max-num="6" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="sizeChange(20)">
        <template #headerRight>
          <a-popover content="导出库存">
            <a-button type="text" style="font-size: 16px; color: #141840">
              <template #icon>
                <icon-download />
              </template>
            </a-button>
          </a-popover>
        </template>
        <template #tableBody>
          <a-table size="mini" class="table-two-line" :data="dataList" @sorter-change="sortChange" row-key="id" :loading="loading" :row-selection="rowSelection" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column title="店铺" #cell="{ record, rowIndex }" :width="120">
                {{ record.shopName }}
              </a-table-column>
              <a-table-column title="平台订单号" #cell="{ record, rowIndex }" :width="120">
                <div class="highlight" style="cursor: pointer" @click="toDetail(record)">
                  {{ record.platformOrderNumber }}
                </div>
              </a-table-column>
              <a-table-column title="国家" #cell="{ record, rowIndex }" :width="100">
                {{ record.countryName }}
              </a-table-column>
              <a-table-column title="省州(邮编)" #cell="{ record, rowIndex }" :width="120">
                <span>
                  {{ record.stateOrRegion }}
                </span>
                <span v-if="record.postalCode"> ({{ record.postalCode }}) </span>
              </a-table-column>
              <!-- <a-table-column title="承运商/跟踪号" #cell="{ record, rowIndex }" :width="120">
                {{ rowIndex + 1 }}
              </a-table-column> -->
              <a-table-column title="下单时间（+8）" data-index="gmtPurchase" :sortable="{ sortDirections: ['ascend', 'descend'] }" #cell="{ record, rowIndex }" :width="140">
                {{ $setTime(record.gmtPurchase) }}
              </a-table-column>
              <a-table-column title="退货时间" data-index="gmtReturn" :sortable="{ sortDirections: ['ascend', 'descend'] }" #cell="{ record, rowIndex }" :width="140">
                {{ $setTime(record.gmtReturn) }}
              </a-table-column>
              <a-table-column title="LPN" #cell="{ record, rowIndex }" :width="100">
                {{ record.licensePlateNumber }}
              </a-table-column>
              <a-table-column title="图片" #cell="{ record, rowIndex }" :width="80">
                <ImgPopover :src="getProductPic(record)">
                  <template #con>
                    <a-image :preview="false" width="40" height="40" fit="contain" :src="getProductPic(record)" />
                  </template>
                </ImgPopover>
              </a-table-column>
              <a-table-column title="商品名称" #cell="{ record, rowIndex }" :width="120">
                <textLimit :rows="2" position="top">{{ record.productName }}</textLimit>
              </a-table-column>
              <a-table-column title="ASIN/MSKU" #cell="{ record, rowIndex }" :width="120">
                <div>
                  <textLimit class="highlight" :rows="1" position="top">{{ record.asin }}</textLimit>
                </div>
                <div>
                  <textLimit class="highlight" :rows="1" position="top">{{ record.msku }}</textLimit>
                </div>
              </a-table-column>
              <a-table-column title="FNSKU" #cell="{ record, rowIndex }" :width="120">
                <div class="highlight">{{ record.fnsku }}</div>
              </a-table-column>
              <a-table-column title="SKU/类目" #cell="{ record, rowIndex }" :width="120">
                <ShowSpuDetailBySku :val="record.productSku" :showLimit="true" :rows="1" />
                <div class="highlight">{{ record.productCategoryName }}</div>
              </a-table-column>
              <a-table-column title="销售员" #cell="{ record, rowIndex }" :width="80">
                {{ record.salerName }}
              </a-table-column>
              <a-table-column title="退货数量" #cell="{ record, rowIndex }" :width="80">
                {{ record.qtyReturn }}
              </a-table-column>
              <a-table-column title="库存属性" #cell="{ record, rowIndex }" :width="80">
                {{ filterWarehouseProperty(record) }}
              </a-table-column>
              <a-table-column title="退货原因" #cell="{ record, rowIndex }" :width="140">
                <textLimit :rows="2" position="top">{{ record.reason }}</textLimit>
              </a-table-column>
              <a-table-column title="退货状态" #cell="{ record, rowIndex }" :width="140">
                {{ record.status }}
              </a-table-column>
              <a-table-column title="买家备注" #cell="{ record, rowIndex }" :width="140">
                <textLimit :rows="2" position="top">{{ record.customerComments }}</textLimit>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import { useRouter } from 'vue-router'
  import { fbaOrderReturn, findShopMarketByParam } from '@/api/order'
  import { getShopMarketAll } from '@/api/base'
  import { findShopListByShare, findWarehouseListByParam } from '@/api/warehouse'
  import { getOrganizesUser } from '@/api/system'
  import { countriesOptions } from '@/utils/countries'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import textLimit from '@/components/textLimit.vue'
  import _ from 'lodash-es'
  import { TabData } from '@arco-design/web-vue/es/tabs/interface'
  import { TableData } from '@arco-design/web-vue'
  export default defineComponent({
    components: {
      FilterTable,
      TableWrap,
      textLimit,
    },
    setup() {
      const router = useRouter()
      const data: any = reactive({
        filterItem: [
          {
            key: 'marketplaceIdList',
            label: '站点',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'sellerMarketId',
            label: '店铺',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            type: 'input_keyword',
            key: 'mskuList',
            keyItems: [
              { label: 'MSKU', value: 'mskuList' },
              { label: 'FNSKU', value: 'fnskuList' },
              { label: '商品名称', value: 'productNameList' },
              { label: 'LPN', value: 'licensePlateNumberList' },
              { label: 'SKU', value: 'productSkuList' },
            ],
            keyWidth: '90',
            value: ref(),
            placeholder: '请输入',
            label: 'MSKU',
            width: 160,
            isMultiple: true,
          },
          {
            type: 'input_keyword',
            key: 'platformOrderNumberList',
            keyItems: [{ label: '平台单号', value: 'platformOrderNumberList' }],
            keyWidth: '90',
            value: ref(),
            placeholder: '请输入',
            label: '平台单号',
            width: 160,
            isMultiple: true,
          },
          {
            key: 'detailedDisposition',
            label: '库存属性',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [
              { label: '可用', value: 'SELLABLE' },
              { label: '残缺', value: 'DAMAGED' },
              { label: '买家损坏', value: 'CUSTOMER_DAMAGED' },
              { label: '不良品', value: 'DEFECTIVE' },
              { label: '承运人损坏', value: 'CARRIER_DAMAGED' },
              { label: '过期', value: 'EXPIRED' },
            ],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'statusList',
            label: '退货状态',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [
              { label: '无状态', value: 'NONE' },
              { label: 'Unit returned to inventory', value: 'Unit returned to inventory' },
              { label: 'Reimbursed', value: 'Reimbursed' },
              { label: 'Pending Repackaging', value: 'Pending Repackaging' },
              { label: 'Repackaged Successfully', value: 'Repackaged Successfully' },
            ],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'reasonList',
            label: '退货原因',
            value: ref(),
            type: 'input_search',
            width: '100%',
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'salerIdList',
            label: '销售员',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            type: 'keyword_date_range',
            key: 'gmtPurchase',
            keyItems: [
              { label: '下单时间(+8)', value: 'gmtPurchase' },
              { label: '下单时间(+0)', value: 'gmtPurchase0' },
              { label: '退货时间', value: 'gmtReturn' },
            ],
            keyWidth: '120',
            value: ref(),
            placeholder: '请输入',
            label: '下单时间(+8)',
            width: 160,
            isMultiple: true,
          },
        ],
        columns: [
          { title: '店铺', dataIndex: 'name', width: '130px' },
          { title: '图片', dataIndex: 'name', width: '140px' },
          { title: '产品名称/SKU', dataIndex: 'name', width: '250px' },
          { title: 'MSKU/FNSKU', dataIndex: 'name', width: '250px' },
          { title: 'SPU/类目', dataIndex: 'name', width: '200px' },
          { title: '品牌', dataIndex: 'name', width: '110px' },
          // { title: '单位', dataIndex: 'name', width: 120 },
          { title: '产品类型', dataIndex: 'name', width: '110px' },
          { title: '数量', dataIndex: 'name', width: '140px' },
          { title: '库存属性', dataIndex: 'name', width: '140px' },
          { title: '单位成本', dataIndex: 'name', width: '120px' },
          { title: '货值', dataIndex: 'name', width: '80px' },
          { title: '上架货位', dataIndex: 'name', width: '120px' },
        ],
        dataList: [],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        expandable: {},
        loading: false,
        isCollapse: false,
        info: {
          type: 'in',
          id: '',
        },
        id: '',
        searchValue: {},
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
      })

      const sortChange = (item: any, extra: any) => {
        if (extra) {
          data.searchValue.sortField = item
          data.searchValue.sortType = extra == 'ascend' ? '1' : '-1'
        } else {
          data.searchValue.sortField = ''
          data.searchValue.sortType = ''
        }
        getList()
      }

      const searchByVal = (info: any) => {
        let obj = _.cloneDeep(info)
        data.searchValue = info
        if (data.searchValue.startDate) {
          data.searchValue.startDate = `${data.searchValue.startDate} 00:00:00`
          data.searchValue.endDate = `${data.searchValue.endDate} 23:59:59`
        }
        data.pageNation.pageNum = 1
        getList()
      }
      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }
      const getMarketList = async () => {
        const res = await getShopMarketAll()
        let arr = res.data.map((e: any) => {
          e.label = e.marketplaceName
          e.value = e.marketplaceId
          return e
        })
        data.filterItem[0].optionItems = arr
      }

      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          let arr = res.data?.records
          arr.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          data.filterItem[7].optionItems = arr
        }
      }

      const getShopListByShare = async () => {
        const res = await findShopMarketByParam({})
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.shopName
          e.value = e.sellerMarketId
        })
        data.filterItem[1].optionItems = arr
      }

      const getList = async () => {
        let params = {
          ...data.searchValue,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        const res = await fbaOrderReturn(params)
        data.dataList = res?.data?.records
        data.pageNation.total = res?.data?.total
        data.dataList.map((e: any) => {
          let obj = countriesOptions.find((el) => e.countryCode == el.short)
          e.countryName = obj?.name
          return e
        })
        data.loading = false
      }

      const getProductPic = (item: TableData) => {
        return item?.productPic || ''
      }

      const filterWarehouseProperty = (item: TableData) => {
        let obj = {
          SELLABLE: '可用',
          DAMAGED: '残缺',
          CUSTOMER_DAMAGED: '买家损坏',
          DEFECTIVE: '不良品',
          CARRIER_DAMAGED: '承运人损坏',
          EXPIRED: '过期',
        }
        return obj[item.detailedDisposition]
      }

      const toDetail = (item: any) => {
        if (!item.orderId) {
          return
        }
        router.push({
          path: '/order/fbaOrder/components/fbaOrderDetail',
          query: {
            id: item.orderId,
          },
        })
      }

      getMarketList()
      getShopListByShare()
      getUSerList()
      getList()

      return {
        ...(toRefs(data) as any),
        searchByVal,
        changePage,
        sizeChange,
        sortChange,
        getProductPic,
        filterWarehouseProperty,
        toDetail,
      }
    },
  })
</script>

<style lang="less" scoped>
  .order-con {
    height: calc(100vh - @menuAndTabHeight);
    width: 100%;

    .item-detail {
      min-height: 56px;
      width: 100%;
      border-bottom: 1px solid #e5e6eb;
    }
  }
</style>
